package com.start.form.engine.admin.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.start.common.api.Result;
import com.start.common.configs.StartTokenConfig;
import com.start.common.dataImport.*;
import com.start.common.dataRule.DataQueryConstructor;
import com.start.common.dataRule.StartQueryWrapper;
import com.start.common.dic.DictMapperParams;
import com.start.common.dic.DictMapperParamsUtils;
import com.start.form.engine.core.StartFormEngine;
import com.start.form.engine.core.model.StartFormConfigModel;
import com.start.security.StartPermissionAuthService;
import com.start.security.StartTokenTools;
import com.start.security.annotations.DataPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/start/formEngine/form/data")
public class DynamicFormDataController {

    @Autowired
    private StartFormEngine formEngine;
    @Autowired
    private StartPermissionAuthService permissionAuthService;

    @Autowired
    private StartTokenConfig tokenConfig;
    @Autowired
    private StartTokenTools tokenTools;

    @GetMapping("/page/{tableId}")
    @DataPermission(value = "views/start/formEngine/data/BusMenuIndex", variable = "tableId")
    public Result<?> page(@PathVariable("tableId") String tableId, Page<List<Map<String, String>>> page) {
        StartQueryWrapper startQueryWrapper = DataQueryConstructor.createStartQueryWrapper();
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "info")) {
            throw new AccessDeniedException("无权限访问");
        }
        return Result.ok(formEngine.getTableDataEngineService(form).page(form, page, startQueryWrapper));
    }

    @GetMapping("/list/{tableId}")
    @DataPermission(value = "views/start/formEngine/data/BusMenuIndex", variable = "tableId")
    public Result<?> list(@PathVariable("tableId") String tableId) {
        StartQueryWrapper startQueryWrapper = DataQueryConstructor.createStartQueryWrapper();
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "info")) {
            throw new AccessDeniedException("无权限访问");
        }
        return Result.ok(formEngine.getTableDataEngineService(tableId).list(form, startQueryWrapper));
    }

    @GetMapping("/getOne/{tableId}")
    public Result<?> getOne(@PathVariable("tableId") String tableId) {
        StartQueryWrapper startQueryWrapper = DataQueryConstructor.createStartQueryWrapper();
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "info")) {
            throw new AccessDeniedException("无权限访问");
        }
        return Result.ok(formEngine.getTableDataEngineService(form).getOne(form, startQueryWrapper));
    }

    @GetMapping("/info/{tableId}/{id}")
    public Result<?> info(@PathVariable("tableId") String tableId, @PathVariable("id") String id) {
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "info")) {
            throw new AccessDeniedException("无权限访问");
        }
        return Result.ok(formEngine.getTableDataEngineService(form).getById(form, id));
    }

    @PutMapping("/updateById/{tableId}/{id}")
    public Result<?> updateById(@PathVariable("tableId") String tableId, @PathVariable("id") String id, @RequestBody JSONObject data) {
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "edit")) {
            throw new AccessDeniedException("无权限访问");
        }
        formEngine.getTableDataEngineService(form).updateById(form, id, data);
        return Result.ok();
    }

    @DeleteMapping("/deleteById/{tableId}/{id}")
    public Result<?> deleteById(@PathVariable("tableId") String tableId, @PathVariable("id") String id) {
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "delete")) {
            throw new AccessDeniedException("无权限访问");
        }
        formEngine.getTableDataEngineService(form).removeById(form, id);
        return Result.ok();
    }

    @PostMapping("/add/{tableId}")
    public Result<?> add(@PathVariable("tableId") String tableId, @RequestBody JSONObject data) {
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "add")) {
            throw new AccessDeniedException("无权限访问");
        }
        return Result.ok(formEngine.getTableDataEngineService(form).save(form, data));
    }

    @GetMapping("/downloadTemplate/{tableId}")
    public void downloadTemplate(@PathVariable("tableId") String tableId, HttpServletResponse response) {
        StartFormConfigModel form = formEngine.getForm(tableId);
        if (!checkPermission(form, "downloadTemplate")) {
            throw new AccessDeniedException("无权限访问");
        }
        String fileTemplate = form.getName() + "数据导入模板.xlsx";
        DictMapperParams excelMapperParams = DictMapperParamsUtils.getExcelMapperParams(form.getFormOption(), ExcelActionType.EXCEL_EXPORT, tokenConfig, tokenTools.getCurrentUserToken());
        ImportExportUtils.setHttpServletResponseToFile(response, fileTemplate);
        try {
            ImportExportUtils.createImportTemplate(excelMapperParams, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/importExcel/{tableId}")
    public Result<?> importExcel(@PathVariable("tableId") String tableId, @RequestBody DataImportEntity entity) {
//        List<String> filePaths = entity.getFilePath();
//        if (filePaths == null || filePaths.size() < 1) return Result.ok();
//        StartFormConfigModel form = formEngine.getForm(tableId);
//        if (!checkPermission(form, "importExcel")) {
//            throw new AccessDeniedException("无权限访问");
//        }
//        DictMapperParams excelMapperParams = DictMapperParamsUtils.getExcelMapperParams(form.getFormOption(), ExcelActionType.EXCEL_EXPORT, tokenConfig, tokenTools.getCurrentUserToken());
//        StartExcelImport excelReadData = new StartExcelImport(excelMapperParams, filePaths.get(0));
//        excelReadData.setListener(row -> formEngine.getTableDataEngineService(form).save(form, row));
//        excelReadData.start();
//        log.info("文件导入:");
        return Result.ok();
    }

    @GetMapping("/exportExcel/{tableId}")
    @DataPermission(value = "views/start/formEngine/data/BusMenuIndex", variable = "tableId")
    public void exportExcel(@PathVariable("tableId") String tableId, HttpServletResponse response) {

//        StartQueryWrapper queryWrapper = DataQueryConstructor.createStartQueryWrapper();
//        StartFormConfigModel form = formEngine.getForm(tableId);
//        if (!checkPermission(form, "exportExcel")) {
//            throw new AccessDeniedException("无权限访问");
//        }
//        String fileName = LocalDateTimeUtil.format(LocalDate.now(), "yyyy年MM月dd日HH时mm分") + "导出" + form.getName() + ".xlsx";
//        ImportExportUtils.setHttpServletResponseToFile(response, fileName);
//        long count = formEngine.getTableDataEngineService(form).count(form, queryWrapper);
//        DictMapperParams excelMapperParams = DictMapperParamsUtils.getExcelMapperParams(form.getFormOption(), ExcelActionType.EXCEL_EXPORT, tokenConfig, tokenTools.getCurrentUserToken());
//        StartStartExcelExport startExcelExport = new StartStartExcelExport(excelMapperParams);
//        startExcelExport.setListener(new StartExcelExportListener() {
//            /**
//             * 数据写入完毕
//             */
//            @Override
//            public void onEnd(ExcelWriter writer) {
//                try {
//                    writer.flush(response.getOutputStream());
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        startExcelExport.start();
//        if (count < 100) {
//            List<JSONObject> list = formEngine.getTableDataEngineService(form).list(form, queryWrapper);
//            for (JSONObject item : list) {
//                startExcelExport.writeRow(item);
//            }
//            startExcelExport.writeEnd();
//        } else {
//            Page page = new Page();
//            page.setCurrent(1);
//            page.setSize(100);
//            do {
//                page = formEngine.getTableDataEngineService(form).page(form, page, queryWrapper);
//                List records = page.getRecords();
//                page.getRecords().forEach(item -> {
//                    startExcelExport.writeRow(JSONObject.parseObject(JSONObject.toJSONString(item)));
//                });
//                page.setCurrent(page.getCurrent() + 1);
//            } while (page.getCurrent() <= page.getPages());
//            startExcelExport.writeEnd();
//        }

    }

    private boolean checkPermission(StartFormConfigModel model, String permissionCode) {
        if (model == null) return true;
        if (StringUtils.isEmpty(permissionCode)) {
            return true;
        }
        if (permissionAuthService.hasPermission(model.getId() + ":" + permissionCode)) {
            return true;
        }
        if (StringUtils.isEmpty(model.getCreateBy())) {
            return true;
        }
        if (StartTokenTools.getCurrentUser(false) == null) {
            return false;
        }
        return model.getCreateBy().equals(tokenTools.getCurrentUserId());
    }
}
